package com.mjlf.mr.speed;

import org.apache.commons.lang.time.DateUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName: Speed
 * @Author: majun
 * @CreateDate: 2018/12/18 11:05
 * @Version: 1.0
 * @Description: TODO
 */

public class Speed implements WritableComparable<Speed> {
    private String time;
    private String carN;
    private Double speedNum;

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getCarN() {
        return carN;
    }

    public void setCarN(String carN) {
        this.carN = carN;
    }

    public Double getSpeedNum() {
        return speedNum;
    }

    public void setSpeedNum(Double speedNum) {
        this.speedNum = speedNum;
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
//        String str = this.time + "|" + this.carN + "|" + this.speedNum;
//        dataOutput.writeBytes(str);
        dataOutput.writeUTF(this.time);
        dataOutput.writeUTF(this.carN);
        dataOutput.writeDouble(this.speedNum);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
//       String str = dataInput.readLine();
//       String[] strs = str.split("\\|");
//       this.time = strs[0];
//       this.carN = strs[1];
//       this.speedNum = Double.parseDouble(strs[2]);
        this.time = dataInput.readUTF();
        this.carN = dataInput.readUTF();
        this.speedNum = dataInput.readDouble();
    }

    @Override
    public int compareTo(Speed o) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date zDate = sdf.parse(this.time);
            Date nDate = sdf.parse(o.getTime());

            if(DateUtils.isSameDay(zDate, nDate)){
                return 0;
            }else {
                if(zDate.before(nDate)){
                    return 1;
                }else {
                    return -1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public String toString() {
        return "Speed{" +
                "time='" + time + '\'' +
                ", carN='" + carN + '\'' +
                ", speedNum=" + speedNum +
                '}';
    }
}
